/*
  Compilarea si editarea de legaturi se face cu comanda:
  > gcc sursa.c -lncurses -o executabil

*/
#include <ncurses.h>
#include <stdlib.h>
#include "soapH.h"
#include "TesteService.nsmap"

#include <errno.h>
#include <ctype.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>


/* variabile globale */
WINDOW *autentif;
WINDOW *statuswin;
WINDOW *win0;
WINDOW *win1;
WINDOW *punctajf;

int startx,starty,nrfer,nrintrebare;

char *rasp,*nrintr,*r1,*r2,*r3,*intr,*mes,*opt1,*opt2,*opt3,lit[20];
long idutz;

struct soap soap;

#define PORT "4444" //nr. portului
#define BACKLOG 10 //dr de conexiuni
#define MAXMSG 1000 //lungimea maxima a mesajului
#define DEFAULTSOCKET "/tmp/DEFAULT.sock"

 void reverse(char s[])
 {
     int i, j;
     char c;

     for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
         c = s[i];
         s[i] = s[j];
         s[j] = c;
     }
 }

void itoa(int n, char s[])
 {
     int i, sign;

     if ((sign = n) < 0)  /* record sign */
         n = -n;          /* make n positive */
     i = 0;
     do {       /* generate digits in reverse order */
         s[i++] = n % 10 + '0';   /* get next digit */
     } while ((n /= 10) > 0);     /* delete it */
     if (sign < 0)
         s[i++] = '-';
     s[i] = '\0';
     reverse(s);
 }

void parseazaRaspuns(char *str)
	{
		int i;
               // char val[500][500],valoare[100][100];
                char *msg1,*msg2,*msg3,*msg4,*msg5;

msg1=malloc(500);
msg2=malloc(500);
msg3=malloc(500);
msg4=malloc(500);
msg5=malloc(500);

		mes=strtok(str,"&");
                for(i=0;mes!=NULL;i++)
                 {
                   if (i==0) strcpy(msg1,mes);
if (i==1) strcpy(msg2,mes);
if (i==2) strcpy(msg3,mes);
if (i==3) strcpy(msg4,mes);
if (i==4) strcpy(msg5,mes);
                  mes=strtok(NULL,"&");
                 }

               while(strtok(msg1,"=")!= NULL)
               {
                nrintr=strdup(msg1);
                msg1=strtok(NULL,"=");
              }
              if(strcmp(strtok(msg2,"="),"intr")==0)
               {
                msg2=strtok(NULL,"****");
                intr=strdup(msg2);
              }
              if(strcmp(strtok(msg3,"="),"r1")==0)
               {
                msg3=strtok(NULL,"=");
                r1=strdup(msg3);
              }
              if(strcmp(strtok(msg4,"="),"r2")==0)
               {
                msg4=strtok(NULL,"=");
                r2=strdup(msg4);
              }

if(strcmp(strtok(msg5,"="),"r3")==0)
               {
                msg5=strtok(NULL,"=");
                r3=strdup(msg5);
              }

              opt1="0";
              opt2="0";
              opt3="0";
}
//deseneaza fer de autentificare
void init_grafica_fer_autentificare(void)
{

   start_color();

    if( COLOR_PAIRS > 2)
    {
	init_pair(2,COLOR_BLACK,COLOR_WHITE);
        wbkgd(autentif,' ' | A_BOLD | COLOR_PAIR(2) );
    }
    else
	wbkgd(autentif,' ' | A_REVERSE );

    box(autentif,'|','-');
    mvwprintw(autentif, 3, 3, "NUME:");
    mvwprintw(autentif, 6, 3, "PRENUME:");
    //mvwprintw(autentif, 9, 3, "CNP:");
    wattron(autentif, A_REVERSE);
    mvwprintw(autentif, 12, 20, "START");
    wattroff(autentif, A_REVERSE);

    wrefresh(autentif);
}

//deseneaza ferestrele pentru test
void init_grafica_ferestre (void)
{

    /* 1: setarea background-ului ferestrelor */
    start_color();

    if( COLOR_PAIRS > 1)
    {
	init_pair(1,COLOR_BLACK,COLOR_WHITE);
        wbkgd(win0,' ' | A_BOLD | COLOR_PAIR(1) );
    }
    else
	wbkgd(win0,' ' | A_REVERSE );

    if( COLOR_PAIRS > 2)
    {
	init_pair(2,COLOR_WHITE,COLOR_BLACK);
        wbkgd(win1,' ' | A_BOLD | COLOR_PAIR(2) );
    }
    else
            wbkgd(win1,' ' | A_REVERSE );

    if( COLOR_PAIRS > 3)
    {
	init_pair(3,COLOR_BLACK,COLOR_WHITE);
        wbkgd(statuswin,' ' | A_BOLD | COLOR_PAIR(3) );
    }
    else
            wbkgd(statuswin,' ' | A_REVERSE );

    /* 2: desenarea de chenare in jurul ferestrelor si adaugarea de texte */

    box(win0,'|','=');
    wattron(win0, A_REVERSE);
    mvwprintw(win0, 10, 5, "  ");
    mvwprintw(win0, 13, 5, "  ");
    mvwprintw(win0, 16, 5, "  ");
    mvwprintw(win0, 18, 40, "VALIDARE");
    mvwprintw(win0, 18, 30, "STOP");
    wattroff(win0, A_REVERSE);

    box(win1,'-','|');
    mvwprintw(win1,2,2,"Punctaj");

	box(statuswin,'*','*');
        wattron(statuswin, A_REVERSE);
	mvwprintw(statuswin, 1, 2, "1");
	mvwprintw(statuswin, 1, 5, "2");
	mvwprintw(statuswin, 1, 8, "3");
	mvwprintw(statuswin, 1, 11, "4");
	mvwprintw(statuswin, 1, 14, "5");
	mvwprintw(statuswin, 1, 17, "6");
	mvwprintw(statuswin, 1, 20, "7");
	mvwprintw(statuswin, 1, 23, "8");
	mvwprintw(statuswin, 1, 26, "9");
	mvwprintw(statuswin, 1, 29, "10");
        wattroff(statuswin, A_REVERSE);

    /* 3: refresh-ul ferestrelor */
    wrefresh(win0);

    wrefresh(win1);

    wrefresh(statuswin);
}

//deseneaza fereastra de punctaj final
void init_grafica_fer_punctajf(void)
{

   start_color();

    if(COLOR_PAIRS > 2)
    {
	init_pair(2,COLOR_BLACK,COLOR_WHITE);
        wbkgd(punctajf,' ' | A_BOLD | COLOR_PAIR(2) );
    }
    else
    wbkgd(punctajf,' ' | A_REVERSE );

    box(punctajf,'*','*');
    mvwprintw(punctajf, 3, 3, "PUNCTAJ FINAL:");
    wattron(punctajf, A_REVERSE);
    mvwprintw(punctajf, 9, 9, "OK");
    wattroff(punctajf, A_REVERSE);

    wrefresh(punctajf);
}

int apasatStart(int y,int x)
{
    int i,j;

   i=startx+20;
   j=starty+12;

   if (y==j && x>=i && x<=i+strlen("START"))
    {
         return 1;
    }
return 0;
}

int apasatValidare(int y,int x)
{
    int i,j;


   i=43;
   j=20;

   if (y==j && x>=i && x<=i+strlen("VALIDARE"))
    {
         nrfer=-1;
	 if (strcmp(opt1,"1")==0)
	    strcpy(rasp,opt1);
	 if(strcmp(opt1,"1")==0)
	    strcat(rasp,opt2);
	 if(strcmp(opt1,"0")==0 && strcmp(opt2,"1")==0)
	   strcpy(rasp,opt2);
	 if(strcmp(opt1,"0")==0 && strcmp(opt2,"0")==0)
	   strcpy(rasp,opt3);
	 else
	    strcat(rasp,opt3);
         return 1;
    }
return 0;

}

int apasaStop(int y,int x)
{
    int i,j;


   i=33;
   j=20;

   if (y==j && x>=i && x<=i+strlen("STOP"))
    {
          nrfer=-1;
          return 1;
    }
return 0;

}
void alegeRasp(int y,int x)
{
    int i,j;


   i=8;
   j=12;


   if (y==12 && x>=i && x<=i+strlen("  "))
    {     wattron(win0, A_REVERSE);
          mvwprintw(win0, 10, 5, "x");
          nrfer=-1;
          wattroff(win0, A_REVERSE);
          wrefresh(win0);
         opt1="1";
    }
    if (y==15 && x>=i && x<=i+strlen("  "))
    {    wattron(win0, A_REVERSE);
          mvwprintw(win0, 13, 5, "x");
          nrfer=-1;
          wattroff(win0, A_REVERSE);
          wrefresh(win0);
          opt2="1";
    }
    if (y==18 && x>=i && x<=i+strlen("  "))
    {    wattron(win0, A_REVERSE);
          mvwprintw(win0, 16, 5, "x");
          nrfer=-1;
          wattroff(win0, A_REVERSE);
          wrefresh(win0);
          opt3="1";
    }

}

char *apasatNr(int y,int x)
{
    char *nrintr=malloc(80);
    int i,j;


   j=26;
   strcpy(nrintr,"1");
   if (y==j && x==3)
    {
          nrfer=-1;
          strcpy(nrintr,"1");
    }
   if (y==j && x==6)
    {
          nrfer=-1;
         strcpy(nrintr,"2");
    }
   if (y==j && x==9)
    {
           strcpy(nrintr,"3");
          nrfer=-1;

    }
  if (y==j && x==12)
    {    strcpy(nrintr,"4");

          nrfer=-1;
    }
if (y==j && x==15)
    {
         strcpy(nrintr,"5");
          nrfer=-1;

    }
if (y==j && x==18)
    {
         strcpy(nrintr,"6");
          nrfer=-1;
    }
if (y==j && x==21)
    {
         strcpy(nrintr,"7");
          nrfer=-1;
    }
if (y==j && x==24)
    {
         strcpy(nrintr,"8");
          nrfer=-1;
    }
if (y==j && x==27)
    {    strcpy(nrintr,"9");
           nrfer=-1;
    }
if (y==j && x>=30 && x<=31)
    {
          nrfer=-1;
         strcpy(nrintr,"10");
    }

return nrintr;

}
/*************************************
* Functia principala a programului   *
*************************************/

int main()
{
    /* variabile locale */
    int	tasta,i,j;
    mmask_t mask;
    MEVENT event;
    char *nume="Costache ";
    char *prenume="Emanuel";
    char *cnp="1880923204488";
    char *nrintrcere=malloc(20);
    char *nr=malloc(80);

    char *response=malloc(500);
     char *nrpct;
	char *control=malloc(80);
opt1=malloc(20);
opt2=malloc(20);
opt3=malloc(20);
r1=malloc(500);
r2=malloc(500);
r3=malloc(500);
rasp=malloc(500);
nrintr=malloc(20);

//idutz=malloc(10);
 intr=malloc(500);
nrintrcere="1";



   soap_init(&soap);

   nrfer=0;
   startx=0;
   starty=0;



    /* initializarea lucrului cu ncurses;
       returneaza un pointer la obiectul stdscr (screen-ul standard) */
    if( NULL == initscr() )
    {
	fprintf(stderr,"Eroare la initializarea ncurses !\n");
	return 1;
    }

    /* setarea unor optiuni de intrare
       Help: man curs_inopts    */
    cbreak();	/* citire in mod caracter, nu linie */
    noecho();	/* citire fara ecou pe ecran */

    /* setarea unor optiuni de intrare/iesire
       Help: man curs_outopts    */
    //nonl();	/* nu mai converteste ENTER in NEWLINE('\n') */

    /* crearea ferestrelor */

keypad(stdscr, TRUE);
box(stdscr, 0, 0);

  startx = 35/2;
  starty = 15/2;

autentif = newwin(15,50,starty,startx);
    if( autentif == NULL )
    {
	endwin();
	fprintf(stderr,"Eroare la crearea ferestrei pentru autentificare.\n");
        exit(1);
    } else {
    keypad(autentif, TRUE);
  }


   win0 = newwin(20,100,2,3);
    if( win0 == NULL )
    {
	endwin();
	fprintf(stderr,"Eroare la crearea ferestrei pentru afisare intrebari.\n");
        exit(1);
    } else {
    keypad(win0, TRUE);
  }

   win1 = newwin(6,20,2,104);
    if( win1 == NULL )
    {
	endwin();
	fprintf(stderr,"Eroare la crearea ferestrei pentru punctaj.\n");
        exit(1);
    }

    statuswin = newwin(3, 35, 25, 1);
    if( statuswin == NULL )
    {
	endwin();
	fprintf(stderr,"Eroare la crearea ferestrei de navigare in intrebari.\n");
        exit(1);
    }
    else {
     keypad(statuswin,TRUE);
   }

    punctajf = newwin(12, 20, 10, 30);
    if( punctajf  == NULL )
    {
	endwin();
	fprintf(stderr,"Eroare la crearea ferestrei de punctaj final.\n");
        exit(1);
    }
    else {
     keypad(punctajf,TRUE);
   }

    /* ascunderea cursorului */
//    curs_set(0); /* face cursorul invizibil; Help: man curs_kernel */
    leaveok(autentif,TRUE);
    leaveok(win0,TRUE); /* Help: man curs_outopts */
    leaveok(win1,TRUE);
    leaveok(statuswin,TRUE);
    leaveok(punctajf,TRUE);

    mask = mousemask(ALL_MOUSE_EVENTS, NULL);

   /* desenarea initiala a ferestrelor */
  init_grafica_fer_autentificare();
  j=3;
  i=11;

    /* bucla principala a programului */
    do
    {
     if (nrfer==0) {
         tasta=wgetch(autentif);
        }
    if (nrfer==1) tasta=wgetch(win0);
    if (nrfer==2) tasta=wgetch(win1);
    if (nrfer==-1) tasta=getch();

       if(tasta == KEY_MOUSE)
        {
			getmouse(&event);

			if (nrfer==-1)
			{
			  if(event.y>=2 && event.y<=22 && event.x>=3 && event.x<=53)
				   nrfer=1;
			   else
				   nrfer=2;
			}

			if (nrfer==0)
			{
			 if (apasatStart(event.y,event.x)==1)
				 {
				   nrfer=-1;
				   struct inregistreazaType pers;
				   struct inregistreazaResponseType userid;
				   pers.nume = nume;
				   pers.prenume = prenume;
				   pers.cnp = cnp;
				   soap_call_mySpace__inregistreaza(&soap,"http://localhost:4445/",NULL, &pers, &userid);
				   idutz= userid.userid;
				   delwin(autentif);
				   refresh();
				   init_grafica_ferestre();
				   struct cereintrebareType cere;
				   struct cereintrebareResponseType raspuns;
				   cere.userid = idutz;
				   cere.nrintr = nrintrcere;
//				   raspuns.response = response;
                                   soap_call_mySpace__cereintrebare(&soap,"http://localhost:4445/",NULL,&cere, &raspuns);
                                   response= raspuns.response;

                                   parseazaRaspuns(response);
				   wrefresh(win0);
                                   mvwprintw(win0,5,5,nrintr);
                                   mvwprintw(win0,5,7,intr);
                           mvwprintw(win0,10,7,r1);
		                   mvwprintw(win0,13,7,r2);
		                   mvwprintw(win0,16,7,r3);
		                   wattron(win0, A_REVERSE);
				   mvwprintw(win0, 10, 5, "  ");
				   mvwprintw(win0, 13, 5, "  ");
				   mvwprintw(win0, 16, 5, "  ");
				   wattroff(win0, A_REVERSE);
		                   wrefresh(win0);
				 }
			}
		  if (nrfer==1)
			  {
				  if (apasaStop(event.y,event.x))
					  {
						  init_grafica_fer_punctajf();
						  struct numarpunctefinalType user;
						  struct numarpunctefinalResponseType nrpctf;
						  user.userid = idutz;
						  soap_call_mySpace__numarpunctefinal(&soap,"http://localhost:4445/",NULL,&user, &nrpctf);
						  nrpct= nrpctf.nrpct;
						  mvwprintw(punctajf,6,5,nrpct);
                                                  wrefresh(punctajf);
					  }
				  if  (apasatValidare(event.y,event.x))
					  {
					  struct raspundeType ras;
					  struct raspundeResponseType control;
					  ras.userid = idutz;
					  ras.rasp = rasp;
					  ras.nrintr = nrintr;
//				          ras.control = control;
					  soap_call_mySpace__raspunde(&soap,"http://localhost:4445/",NULL,&ras,&control);

				          struct numarpuncteType user;
				          struct numarpuncteResponseType nnrpct;
					  user.userid = idutz;
					  //nnrpct.nrpct = nrpct;
                                          soap_call_mySpace__numarpuncte(&soap,"http://localhost:4445/",NULL,&user,&nnrpct);
                                          nrpct= nnrpct.nrpct;
                                          mvwprintw(win1,4,2,nrpct);
                                          wrefresh(win1);

					  }
				  	alegeRasp(event.y,event.x);

			   }

			if (nrfer==2)
			{
				if (strcmp(apasatNr(event.y,event.x),"0")!=0)
				{

				  nrintrcere=strdup(apasatNr(event.y,event.x));
				  struct cereintrebareType cere;
    		  	          struct cereintrebareResponseType raspuns;
		 	         cere.userid = idutz;
				   cere.nrintr = nrintrcere;
//				   raspuns.response = response;
                                   soap_call_mySpace__cereintrebare(&soap,"http://localhost:4445/",NULL,&cere, &raspuns);
                                   response= raspuns.response;
					parseazaRaspuns(response);
                                        wrefresh(win0);
					mvwprintw(win0,5,5,"  ");
                                        mvwprintw(win0,5,5,nrintr);
                                        mvwprintw(win0,5,7,"                                                                                                                                              ");
                                            mvwprintw(win0,5,7,intr);
                                            mvwprintw(win0,10,7,"                                                             ");
                                             mvwprintw(win0,10,7,r1);
                                             mvwprintw(win0,13,7,"                                                            ");
                                             mvwprintw(win0,13,7,r2);
                                             mvwprintw(win0,16,7,"                                                             ");
                                             mvwprintw(win0,16,7,r3);
				           wattron(win0, A_REVERSE);
					   mvwprintw(win0, 10, 5, "  ");
					   mvwprintw(win0, 13, 5, "  ");
					   mvwprintw(win0, 16, 5, "  ");
					   wattroff(win0, A_REVERSE);
				           wrefresh(win0);

				}
			}
	   }
	   else
	   {
		   if (tasta==10)
			   {
				   j=j+3;
				   i=12;
                          }
		   else
		   {
			  //sprintf(lit,"%c",tasta);
			  //strcat(nume,(char *)lit);
			  mvwprintw(autentif,j,i,"%c",tasta);
		//	  mvwprintw(autentif,5,3,"%s",nume);
		//	  wrefresh(autentif);
			  i++;
		   }
            }
} while( tasta!=27 );

    /* sfirsitul lucrului cu ncurses;
       pe ecran ramine ceea ce a fost la ultimul refresh !     */

    //delwin(win0);

    //delwin(win1);

//    delwin(statuswin);

  //  delwin(punctajf);

    endwin();

    soap_done(&soap);

    return 0;
}
